package com.light.mytext.mvvp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.light.mytext.R
import com.light.mytext.databinding.ActivityMVVPBinding
import com.light.mytext.utiles.ToastUtils
import kotlinx.android.synthetic.main.activity_m_v_v_p.*

/**
 * NVVP的使用
 */
class MVVPActivity : AppCompatActivity() {
    lateinit var binding: ActivityMVVPBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_m_v_v_p)
        /**
         * ViewModel+DataBinding
         */
        binding.viewModel = MainViewModel()
        /**
         * ViewModel+DataBinding+LiveData(属于Android Jectpack中的lifecycle库)
         */
        val userViewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
        binding.userViewModel = userViewModel
        // 让xml内绑定的LiveData和Observer建立连接，也正是因为这段代码，让LiveData能感知Activity的生命周期
        binding.lifecycleOwner = this
        // 监听ViewModel中user的变化，当它变化时，将TextView重新设置文字
        userViewModel.user.observe(this, Observer {
            tv_name.text = it.name
            tv_age.text = it.age
            tv_sex.text = it.sex
        })
        bt_setname.setOnClickListener {
            var user = User("文阿花", "21", "女")
            userViewModel.user.value = user
            ToastUtils.showInCenter(this,"文阿花")
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        // 在Activity销毁时记得解绑，以免内存泄漏
        binding.unbind()
    }
}

